<!--
 * @Author: Bennty
 * @Date: 2024-08-27 08:47:01
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-11-05 16:02:43
 * @Description: 请填写简介
-->
<template>
    <div class="p-2">
        <transition
            :enter-active-class="proxy?.animate.searchAnimate.enter"
            :leave-active-class="proxy?.animate.searchAnimate.leave"
        >
            <div class="search">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true">
                    <el-form-item prop="productCategoriesType">
                        <el-select v-model="queryParams.productCategoriesType" placeholder="请选择">
                            <el-option v-for="item in typeList" :key="item.id" :label="item.majorName" :value="item.majorType"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="productSubcategoryType">
                        <el-select v-model="queryParams.productSubcategoryType" placeholder="请选择">
                            <el-option v-for="item in subTypeList" :key="item.id" :label="item.subclassName" :value="item.subclassType"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="状态" prop="status">
                        <el-select v-model="queryParams.status" placeholder="请选择">
                            <el-option label="正常" :value="1"></el-option>
                            <el-option label="停用" :value="0"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="模糊查询" prop="specsDetail">
                        <el-input v-model="queryParams.specsDetail" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
                <span class="inventory-amount">库存金额：{{ totalInventoryAmount }} 元</span>
            </div>
            
        </transition>
        <el-card shadow="never">
            <template #header>
                <el-row :gutter="8" class="mb8">
                    <el-col class="header-button-container" :span="1.5">
                        <el-button type="success" plain icon="Plus" @click="handleClickAdd">新增辅材</el-button>
                    </el-col>
                    <el-col class="header-button-container" :span="1.5">
                        <el-button type="primary" plain icon="Download" @click="exportAuxiliaryList">导出</el-button>
                    </el-col>
                </el-row>
            </template>
            <el-table :data="materialList">
                <el-table-column label="状态">
                    <template #default="scope">
                        <!-- <span class="material-status alert" v-if="scope.row.status == '0'">报警</span> -->
                        <span class="material-status" v-if="scope.row.status == '1'">正常</span>
                        <span class="material-status alert" v-else-if="scope.row.status == '0'">停用</span>
                    </template>
                </el-table-column>
                <el-table-column label="材料大类" prop="productCategoriesName"></el-table-column>
                <el-table-column label="材料小类" prop="productSubcategoryName"></el-table-column>
                <el-table-column label="具体名称及规格" prop="specsDetail"></el-table-column>
                <el-table-column label="单价" prop="unit"></el-table-column>
                <el-table-column label="最低库存" prop="lowInventory"></el-table-column>
                <el-table-column label="当前可用库存" prop="currentInventory"></el-table-column>
                <el-table-column label="采购冻结库存" prop="purchaseFreezeInventory"></el-table-column>
                <el-table-column label="生产冻结库存" prop="productFreezeInventory"></el-table-column>
                <el-table-column label="库存金额" prop="totalInventoryAmount">
                    <template #default="scope">
                        <span>{{ scope.row.price * scope.row.currentInventory }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="包装工费" prop="packagingLaborCost"></el-table-column>
                <!-- <el-table-column label="积分" prop="point"></el-table-column> -->
                <el-table-column label="备注" prop="remark"></el-table-column>
                <el-table-column label="操作" width="300">
                    <template #default="scope">
                        <el-tooltip content="编辑" placement="top">
                            <el-button link type="primary" :style="{fontSize:'15px'}"  icon="Edit" @click="handleClickEdit(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button link  :style="{fontSize:'15px',color:'#F75C4E'}"  icon="Delete" @click="handleClickDelete(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip content="入库" placement="top">
                            <el-button link :style="{fontSize:'15px',color:'#FBBBBA'}"  icon="Back" @click="handleClickInStorage(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip content="出库" placement="top">
                            <el-button link :style="{fontSize:'15px',color:'#B886F8'}"  icon="Right" @click="handleClickOutStorage(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip content="采购申请" placement="top">
                            <el-button link :style="{fontSize:'15px',color:'#69AFF0'}"  icon="Goods" @click="handleClickApply(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip content="下包装单" placement="top">
                            <el-button link :style="{fontSize:'15px'}"  icon="Bottom" @click="handleClickOrderPackage(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip content="录入包装件" placement="top">
                            <el-button link :style="{fontSize:'15px'}" type="primary" icon="Tickets" @click="handleClickRecordPackageInformation(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip content="录入不锈钢定制" placement="top">
                            <el-button link :style="{fontSize:'15px'}"  icon="ForkSpoon" @click="handleClickRecordStainlesssteelOrder(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="totalData > 0" :total="totalData" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
                @pagination="getAuxiliaryList" />
        </el-card>
        <addMaterial :visible="addMaterialVisible" :types="typeList" @submit="handleSubmitAdd" @close="handleCloseAdd" />
        <editMaterial :visible="editMaterialVisible" :types="typeList" :data="auxiliaryDetail" @submit="handleSubmitEdit"  @close="handleCloseEdit" />
        <inStorage :visible="inStorageVisible" :data="auxiliaryDetail" @submit="handleSubmitInStorage" @close="handleCloseInStorage" />
        <outStorage :visible="outStorageVisible" :data="auxiliaryDetail" :users="roleKeyUserList" :depts="deptOptions" @submit="handleSubmitOutStorage" @close="handleCloseOutStorage" />
        <purchaseApply :visible="purchaseApplyVisible" :data="auxiliaryDetail" :purchaseApplyList="purchaseApplyList" @submit="handleSubmitApply" @close="handleCloseApply" />
        <recordPackageInformation :visible="recordPackageInformationVisible" :types="typeList" :bagCatagory="packageBagTotalCatagory" :data="auxiliaryDetail" @submit="handleSubmitRecordPackage" @close="handleCloseRecordPackageInformation" />
        <recordStainlesssteelOrder :visible="recordStainlesssteelOrderVisible" :types="typeList"  :data="auxiliaryDetail" @submit="handleSubmitRecordStainless" @close="handleCloseRecordStainlesssteelOrder" />
        <orderPackage :visible="orderPackageVisible" :data="auxiliaryDetail" :types="typeList" :packageData="packageList" @submit="handleSbumitOrderPackage" @close="handleCloseOrderPackage" />
    </div>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus';
import { AuxiliaryVO } from '@/api/sj/warehouse/auxiliary/types';
import { getTotalCategoryByMaterialTypeApi, getSingleByTotalApi } from '@/api/sj/warehouse/typeManagement';
import { getAuxiliaryListApi ,deleteAuxiliaryApi,getAuxiliaryByIdApi,getPackageDetailApi,getAuxiliaryPurchaseInfoApi } from '@/api/sj/warehouse/auxiliary';
import addMaterial from './components/addMaterial.vue';
import editMaterial from './components/editMaterial.vue';
import inStorage from './components/inStorage.vue';
import outStorage from './components/outStorage.vue';
import purchaseApply from './components/purchaseApply.vue';
import recordPackageInformation from './components/recordPackageInformation.vue';
import recordStainlesssteelOrder from './components/recordStainlesssteelOrder.vue';
import orderPackage from './components/orderPackage.vue';
import useCRMStore from '@/store/modules/crm';
import { listDept } from "@/api/system/dept"
import { getFormattedTimestamp } from '@/utils/dateFormat';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const queryFormRef = ref<FormInstance>();
const data = reactive({
    queryParams:{
        productCategoriesType: undefined,
        productSubcategoryType: undefined,
        inventoryStatus: undefined,
        status: undefined,
        package: undefined,
        specsDetail: undefined,
        pageNum: 1,
        pageSize: 30
    }
});
const { queryParams } = toRefs(data);
const totalInventoryAmount = ref(100000);
const typeList = ref<any[]>([]);
const subTypeList = ref<any[]>([]);
const materialList = ref<AuxiliaryVO[]>([]);
const totalData = ref(0);
const addMaterialVisible = ref(false);
const editMaterialVisible = ref(false);
const auxiliaryDetail = ref<any>({});
const inStorageVisible = ref(false);
const outStorageVisible = ref(false);
const purchaseApplyVisible = ref(false);
const purchaseApplyList = ref<any[]>([]);
const recordPackageInformationVisible = ref(false);
const packageBagTotalCatagory = ref<any>();
const recordStainlesssteelOrderVisible = ref(false);
const stainlesssteelCatagory = ref<any[]>([]);
const orderPackageVisible = ref(false);
const packageList = ref<any[]>([]);
const { getUserListByRoleKey } = useCRMStore();
const { roleKeyUserList } = toRefs(useCRMStore());
const queryDeptParam = ref({
    pageNum: 1,
    pageSize: 999
});
const deptOptions = ref<any>();

const materialType = '2';

/** 获取部门 */
const getDept = async () => {
    const res = await listDept(queryDeptParam.value);
    const data = proxy?.handleTree(res.data, 'deptId');
    deptOptions.value = data;
};

/** 获取材料小类 */
const getSubCategory = async (majorType: string) => {
    const { data } = await getSingleByTotalApi(majorType,'');
    subTypeList.value = data;
};

/** 获取辅材列表 */
const getAuxiliaryList = async () => {
    const { rows, total } = await getAuxiliaryListApi(queryParams.value);
    materialList.value = rows;
    totalData.value = total;
};

watch(()=>queryParams.value.productCategoriesType, (newData)=>{
    if(newData){
        getSubCategory(newData);
        queryParams.value.productSubcategoryType = undefined;
    }
},{deep: true});

/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getAuxiliaryList();
};

const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};

/** 根据材料类型获取大类 */
const getTotalTypes = async () => {
    const { data } = await getTotalCategoryByMaterialTypeApi({materialType: materialType});
    typeList.value = data;
};

/** 导出 */
const exportAuxiliaryList = () => {
    proxy?.download('/system/auxiliaryMaterials/export',{...queryParams.value},`辅材列表${getFormattedTimestamp()}.xlsx`);
};

/** 点击新增 */
const handleClickAdd = () => {
    addMaterialVisible.value = true;
};

const handleSubmitAdd = (result: boolean) => {
    if(result){
        //刷新列表
        getAuxiliaryList();
    }
};

const handleCloseAdd = () => {
    addMaterialVisible.value = false;
};

/** 点击编辑 */
const handleClickEdit = async (row:AuxiliaryVO) => {
    const {data,code} = await getAuxiliaryByIdApi(row.id);
    if(code == 200){
        auxiliaryDetail.value = data;
        editMaterialVisible.value = true;
    };
};

const handleSubmitEdit = (result: boolean) => {
    if(result){
        getAuxiliaryList();
    }
};

const handleCloseEdit = () => {
    editMaterialVisible.value = false;
};

/** 点击删除 */
const handleClickDelete = async (row:AuxiliaryVO) => {
    await proxy?.$modal.confirm("确认要把此条辅材信息放入回收站？");
    const { code } = await deleteAuxiliaryApi(row.id);
    if(code == 200){
        proxy?.$modal.msgSuccess("放入回收站成功");
        getAuxiliaryList();
    };
};

/** 点击入库 */
const handleClickInStorage = async (row:AuxiliaryVO) => {
    const {data,code} = await getAuxiliaryByIdApi(row.id);
    if(code == 200){
        auxiliaryDetail.value = data;
        inStorageVisible.value = true;
    };
};

const handleSubmitInStorage = (result: boolean) => {
    if(result){
        getAuxiliaryList();
    };
};

const handleCloseInStorage = () => {
    inStorageVisible.value = false;
};

/** 点击出库 */
const handleClickOutStorage = async (row:AuxiliaryVO) => {
    const {data,code} = await getAuxiliaryByIdApi(row.id);
    if(code == 200){
        auxiliaryDetail.value = data;
        outStorageVisible.value = true;
    };
};

const handleSubmitOutStorage = (result: boolean) => {
    if(result){
        getAuxiliaryList();
    };
};

const handleCloseOutStorage = () => {
    outStorageVisible.value = false;
};

/** 点击采购申请 */
const handleClickApply = async (row:AuxiliaryVO) => {
    const {data,code} = await getAuxiliaryByIdApi(row.id);
    const purchaseInfo = await getAuxiliaryPurchaseInfoApi(row.id);
    if(code == 200 && purchaseInfo.code == 200){
        auxiliaryDetail.value = data;
        purchaseApplyList.value = purchaseInfo.data;
        purchaseApplyVisible.value = true;
    };
};

const handleSubmitApply = (result: boolean) => {
    if(result){
        getAuxiliaryList();
    };
};

const handleCloseApply = () => {
    purchaseApplyVisible.value = false;
};

/** 点击录入包装件信息 */
const handleClickRecordPackageInformation = async (row:AuxiliaryVO) => {
    const {data,code} = await getAuxiliaryByIdApi(row.id);
    const result = await getTotalCategoryByMaterialTypeApi({materialType: '2,4'});
    packageBagTotalCatagory.value = result.data[0];
    if(code == 200 && packageBagTotalCatagory.value ){
        auxiliaryDetail.value = data;
        recordPackageInformationVisible.value = true;
    };
};

const handleSubmitRecordPackage = (result: boolean) => {
    if(result){
        getAuxiliaryList();
    };
};

const handleCloseRecordPackageInformation = () => {
    recordPackageInformationVisible.value = false;
};

/** 点击录入不锈钢信息 */
const handleClickRecordStainlesssteelOrder = async (row:AuxiliaryVO) => {
    const {data,code} = await getAuxiliaryByIdApi(row.id);
    // 获取刀叉大类
    const result = await getTotalCategoryByMaterialTypeApi({materialType: '2,3'});
    if(code == 200 && result.code == 200){
        auxiliaryDetail.value = data;
        recordStainlesssteelOrderVisible.value = true;
        stainlesssteelCatagory.value = result.data;
    };
};

const handleSubmitRecordStainless = (result: boolean) => {
    if(result){
        getAuxiliaryList();
    };
};

const handleCloseRecordStainlesssteelOrder = () => {
    recordStainlesssteelOrderVisible.value = false;
};

/** 点击下包装订单 */
const handleClickOrderPackage = async (row:AuxiliaryVO) => {
    const auxiliaryResult = await getAuxiliaryByIdApi(row.id);
    const packageResult = await getPackageDetailApi(row.id);
    if(auxiliaryResult.code == 200 && packageResult.code == 200){
        orderPackageVisible.value = true;
        auxiliaryDetail.value = auxiliaryResult.data;
        packageList.value = packageResult.data;
    };
};

const handleSbumitOrderPackage = (result: boolean) => {
    if(result){
        getAuxiliaryList();
    };
};

const handleCloseOrderPackage = () => {
    orderPackageVisible.value = false;
};

onMounted(()=>{
    getTotalTypes();
    getAuxiliaryList();
    getUserListByRoleKey('business_role');
    getDept();
});

</script>

<style lang="scss" scoped>
.inventory-amount{
    font-size: 18px;
    font-weight: 500;
}
.alert{
    color: red;
}
.material-status{
    line-height: 10;
}
</style>